<?php
namespace app\api\controller;

use library\Controller;
use think\facade\Config;
use think\Db;
use app\admin\service\PointService;

class Callback extends Controller{
    public function native_notify()
    {
        if (!$xml = file_get_contents('php://input')) {
            $this->error('Not found DATA');
        }
        $jsonxml = json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA));

        $result = json_decode($jsonxml, true); //转成数组
        if ($result) {
            //如果成功返回了
            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                // 这里写回调更新支付状态以及业务逻辑
                $pay_code = $result['out_trade_no'];
                $order_sn = explode('_',$pay_code)[0];
                $pay_at = strtotime($result['time_end']);
                $pay_no = $result['transaction_id'];
                $attach = json_decode($result['attach'],true);
                if($attach['pay_type'] == 1){
                	//pc网站支付需要判断平台
                	if($attach['platform'] == 1){
                		//大户
                		if ($attach['type'] == 1) {
		                    //社保账单
		                    $this->insbill_update($order_sn, $pay_at, $pay_no,$pay_code);
		                }elseif($attach['type'] == 2) {
		                    //签约订单
		                    $this->package_order_update($order_sn, $pay_at, $pay_no,$pay_code);
		                }elseif($attach['type'] == 3) {
		                    //公司增值订单
		                    $this->cadditionalbill_update($order_sn, $pay_at, $pay_no,$pay_code);
		                }elseif($attach['type'] == 4) {
	                    	//个人补缴订单
		                    $this->makeupbill_update($order_sn, $pay_at, $pay_no,$pay_code);
		                }elseif($attach['type'] == 5) {
		                    //个人增值订单
		                    $this->appreciationbill_update($order_sn, $pay_at, $pay_no,$pay_code);
		                }
                	}else{
                		//独立户
                		$this->send_order_callback($attach['type'],$order_sn, $pay_at, $pay_no,$pay_code);
                	}
                }else{
                	if ($attach['type'] == 1) {
	                    //社保账单
	                    $this->insbill_update($order_sn, $pay_at, $pay_no,$pay_code);
	                }elseif($attach['type'] == 2) {
	                    //签约订单
	                    $this->package_order_update($order_sn, $pay_at, $pay_no,$pay_code);
	                }elseif($attach['type'] == 3) {
	                    //公司增值订单
	                    $this->cadditionalbill_update($order_sn, $pay_at, $pay_no,$pay_code);
	                }elseif($attach['type'] == 4) {
	                    //个人补缴订单
	                    $this->makeupbill_update($order_sn, $pay_at, $pay_no,$pay_code);
	                }elseif($attach['type'] == 5) {
	                    //个人增值订单
	                    $this->appreciationbill_update($order_sn, $pay_at, $pay_no,$pay_code);
	                }
	                
                }
                
                $arr = [
                    'return_code' => 'SUCCESS',
                    'return_msg' => 'OK',
                ];
                return xml($arr);
//              echo $this->ToXml($arr);
            }
        }
    }
    
    /**
     * 发送到独立户系统
     * @param int $type         
     * @param string $order_sn
     * @param string $pay_at
     * @param string $pay_no
     * @param string $pay_code
     * @return string
     */
    private function send_order_callback($type,$order_sn, $pay_at, $pay_no,$pay_code) {
    	$ser_name = $_SERVER['SERVER_NAME'];
        if($ser_name == 'sybptest.wolundehr.com'){
            $url = 'http://sybtest.wolundehr.com/api/callback/native_order_callback';
        }elseif($ser_name == 'sheyoubaopro.wolundehr.com'){
            $url = 'http://sheyoubao.wolundehr.com/api/callback/native_order_callback';
        }else{
        	return false;
        }
        $data = ['type' => $type,'order_sn' => $order_sn,'pay_at'=>$pay_at,'pay_no'=>$pay_no,'pay_code'=>$pay_code];
        http_post($url,$data);
    }
    
    
    
    /**
     * 修改社保账单状态
     * @param string $order_sn 订单编号
     * @param string $pay_at 支付时间
     * @param string $pay_no 支付交易单号
     * @param string $pay_code 真实订单号
     */
    private function insbill_update($order_sn, $pay_at, $pay_no, $pay_code)
    {
    	$insbill = Db::name('system_insbill')->where(['code'=>$order_sn,'is_deleted'=>0,'status'=>[2,3]])->find();
        if ($insbill) {
            Db::startTrans();
            try {           	
				//更新财务账单
				$finbill = Db::name('system_financial_bill')->where(['bill_type'=>1,'jump_id'=>$insbill['id']])->find();
        		//添加明细
        		$arr = [
	        		'finbill_id' => $finbill['id'],
	        		'code' => $finbill['code'],
	        		'company_id' => $finbill['company_id'],
	        		'trade_type' => 1,
	        		'trade_mode' => 3,
	        		'date' => date('Y-m-d',$pay_at),
	        		'amount' => $insbill['receivable_online'],
	        		'cost_type' => 1,
	        		'pay_no' => $pay_no,
	        		'pay_code' => $pay_code
	        	];
	        	$re = Db::name('system_transaction_details')->insert($arr);   
            	//增加对应的账单收入
            	if($re){
            		$arrival = (float)sprintf("%.2f",$finbill['arrival'] + $insbill['receivable_online']);
    				$balance = (float)sprintf("%.2f",$arrival - $finbill['receivable']);
    				Db::name('system_financial_bill')->where(['id'=>$finbill['id']])->update(['arrival'=>$arrival,'balance'=>$balance,'status'=>3]);
    				Db::name('system_insbill')->where(['id'=>$insbill['id']])->update(['arrival'=>$arrival,'balance'=>$balance,'payment_method'=>3,'status'=>4]);
            	}
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
            }
        }
    }
    
    
    
    /**
     * 修改签约订单状态
     * @param string $order_sn 订单编号
     * @param string $pay_at 支付时间
     * @param string $pay_no 支付交易单号
     * @param string $pay_code 真实订单号
     */
    private function package_order_update($order_sn, $pay_at, $pay_no,$pay_code)
    {
    	$order = Db::name('system_package_order')->where(['code'=>$order_sn,'is_deleted'=>0,'status'=>[1,2]])->find();
        if ($order) {
        	if($order['type'] == 1){
        		//签约
        		Db::startTrans();
	            try {           	
					//更新财务账单
					$finbill = Db::name('system_financial_bill')->where(['bill_type'=>2,'jump_id'=>$order['id']])->find();
	        		//添加明细
	        		$arr = [
		        		'finbill_id' => $finbill['id'],
		        		'code' => $finbill['code'],
		        		'company_id' => $finbill['company_id'],
		        		'trade_type' => 1,
		        		'trade_mode' => 3,
		        		'date' => date('Y-m-d',$pay_at),
		        		'amount' => $order['receivable'],
		        		'cost_type' => 2,
		        		'pay_no' => $pay_no,
		        		'pay_code' => $pay_code
		        	];
		        	$re = Db::name('system_transaction_details')->insert($arr);   
	            	//增加对应的账单收入
	            	if($re){
	            		$arrival = (float)sprintf("%.2f",$finbill['arrival'] + $order['receivable']);
	    				$balance = (float)sprintf("%.2f",$arrival - $finbill['receivable']);
	    				Db::name('system_financial_bill')->where(['id'=>$finbill['id']])->update(['arrival'=>$arrival,'balance'=>$balance,'status'=>3]);
	    				Db::name('system_package_order')->where(['id'=>$order['id']])->update(['arrival'=>$arrival,'balance'=>$balance,'payment_method'=>3,'status'=>3]);
	            	}
	                Db::commit();
	            } catch (Exception $e) {
	                Db::rollback();
	            }
        	}else{
        		//续约
        		if($order['setmeal_type'] == 1){
        			//点数套餐
        			$contract = Db::name('system_contract')->where(['company_id'=>$order['company_id'],'status'=>1])->order('id desc')->find();
			        if($contract['setmeal_type'] != 1){
			        	return false;
			        }
			        $package = Db::name('system_package')->where(['id'=>$order['package_id']])->find();
			        if($package['type'] != 1){
			        	return false;
			        }
        			Db::startTrans();
		            try {           	
						//更新财务账单
						$finbill = Db::name('system_financial_bill')->where(['bill_type'=>2,'jump_id'=>$order['id']])->find();
		        		//添加明细
		        		$arr = [
			        		'finbill_id' => $finbill['id'],
			        		'code' => $finbill['code'],
			        		'company_id' => $finbill['company_id'],
			        		'trade_type' => 1,
			        		'trade_mode' => 3,
			        		'date' => date('Y-m-d',$pay_at),
			        		'amount' => $order['receivable'],
			        		'cost_type' => 2,
			        		'pay_no' => $pay_no,
			        		'pay_code' => $pay_code
			        	];
			        	$re = Db::name('system_transaction_details')->insert($arr);   
		            	//增加对应的账单收入
		            	if($re){
		            		$arrival = (float)sprintf("%.2f",$finbill['arrival'] + $order['receivable']);
		    				$balance = (float)sprintf("%.2f",$arrival - $finbill['receivable']);
		    				Db::name('system_financial_bill')->where(['id'=>$finbill['id']])->update(['arrival'=>$arrival,'balance'=>$balance,'status'=>3]);
		    				Db::name('system_package_order')->where(['id'=>$order['id']])->update(['arrival'=>$arrival,'balance'=>$balance,'payment_method'=>3,'status'=>4]);
		    				
					        //新增续约记录
				        	$arr = [
				        		'contract_id' => $contract['id'],        		
				        		'mid' => $contract['mid'],
				        		'company_id' => $contract['company_id'],
				        		'start_date' => date("Y-m-d",time()),
				        		'package_id' => $order['package_id'],
				        		'setmeal_type' => $order['setmeal_type']
				        	];
				        	Db::name('system_contract_renewal')->insert($arr);
				        	//更新点数
				        	Db::name('system_company')->where(['id'=>$order['company_id']])->setInc('point', $package['point']); 
				        	$desc = $contract['code'].'-'.$package['title'];
        					$unique = Db::name('system_company')->where(['id'=>$contract['company_id']])->value('unique');
        					PointService::pointDetAdd($contract['mid'], $contract['mid'], $contract['id'], 1, $package['point'], $desc, $unique);
		            	}
		                Db::commit();
		            } catch (Exception $e) {
		                Db::rollback();
		            }
        		}else{
        			//人数套餐
        			Db::startTrans();
		            try {           	
						//更新财务账单
						$finbill = Db::name('system_financial_bill')->where(['bill_type'=>2,'jump_id'=>$order['id']])->find();
		        		//添加明细
		        		$arr = [
			        		'finbill_id' => $finbill['id'],
			        		'code' => $finbill['code'],
			        		'company_id' => $finbill['company_id'],
			        		'trade_type' => 1,
			        		'trade_mode' => 3,
			        		'date' => date('Y-m-d',$pay_at),
			        		'amount' => $order['receivable'],
			        		'cost_type' => 2,
			        		'pay_no' => $pay_no,
			        		'pay_code' => $pay_code
			        	];
			        	$re = Db::name('system_transaction_details')->insert($arr);   
		            	//增加对应的账单收入
		            	if($re){
		            		$arrival = (float)sprintf("%.2f",$finbill['arrival'] + $order['receivable']);
		    				$balance = (float)sprintf("%.2f",$arrival - $finbill['receivable']);
		    				Db::name('system_financial_bill')->where(['id'=>$finbill['id']])->update(['arrival'=>$arrival,'balance'=>$balance,'status'=>3]);
		    				Db::name('system_package_order')->where(['id'=>$order['id']])->update(['arrival'=>$arrival,'balance'=>$balance,'payment_method'=>3,'status'=>3]);
		            	}
		                Db::commit();
		            } catch (Exception $e) {
		                Db::rollback();
		            }
        		}
        	}
            
        }
    }
    
    
    /**
     * 修改公司增值账单状态
     * @param string $order_sn 订单编号
     * @param string $pay_at 支付时间
     * @param string $pay_no 支付交易单号
     * @param string $pay_code 真实订单号
     */
    private function cadditionalbill_update($order_sn, $pay_at, $pay_no, $pay_code)
    {
    	$insbill = Db::name('system_cadditional_bill')->where(['code'=>$order_sn,'is_deleted'=>0,'status'=>[2,3]])->find();
        if ($insbill) {
            Db::startTrans();
            try {           	
				//更新财务账单
				$finbill = Db::name('system_financial_bill')->where(['bill_type'=>3,'jump_id'=>$insbill['id']])->find();
				if($insbill['cost_type'] == 1){
					$amount = $insbill['receivable_online'];
				}else{
					$amount = $insbill['receivable'];
				}
        		//添加明细
        		$arr = [
	        		'finbill_id' => $finbill['id'],
	        		'code' => $finbill['code'],
	        		'company_id' => $finbill['company_id'],
	        		'trade_type' => 1,
	        		'trade_mode' => 3,
	        		'date' => date('Y-m-d',$pay_at),
	        		'amount' => $amount,
	        		'cost_type' => $insbill['cost_type'],
	        		'pay_no' => $pay_no,
	        		'pay_code' => $pay_code
	        	];
	        	$re = Db::name('system_transaction_details')->insert($arr);   
            	//增加对应的账单收入
            	if($re){
            		$arrival = (float)sprintf("%.2f",$finbill['arrival'] + $amount);
    				$balance = (float)sprintf("%.2f",$arrival - $finbill['receivable']);
    				Db::name('system_financial_bill')->where(['id'=>$finbill['id']])->update(['arrival'=>$arrival,'balance'=>$balance,'status'=>3]);
    				Db::name('system_cadditional_bill')->where(['id'=>$insbill['id']])->update(['arrival'=>$arrival,'balance'=>$balance,'payment_method'=>3,'status'=>4]);
            	}
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
            }
        }
    }
    
    
    /**
     * 修改个人补缴账单状态
     * @param string $order_sn 订单编号
     * @param string $pay_at 支付时间
     * @param string $pay_no 支付交易单号
     * @param string $pay_code 真实订单号
     */
    private function makeupbill_update($order_sn, $pay_at, $pay_no, $pay_code)
    {
    	$insbill = Db::name('system_makeup_bill')->where(['code'=>$order_sn,'is_deleted'=>0,'status'=>[2,3]])->find();
        if ($insbill) {
            Db::startTrans();
            try {           	
				//更新财务账单
				$finbill = Db::name('system_financial_bill_person')->where(['bill_type'=>4,'jump_id'=>$insbill['id']])->find();
        		//添加明细
        		$arr = [
	        		'finbill_id' => $finbill['id'],
	        		'code' => $finbill['code'],
	        		'company_id' => $finbill['company_id'],
	        		'person_id' => $insbill['person_id'],
	        		'trade_type' => 1,
	        		'trade_mode' => 3,
	        		'date' => date('Y-m-d',$pay_at),
	        		'amount' => $insbill['receivable_online'],
	        		'cost_type' => 1,
	        		'pay_no' => $pay_no,
	        		'pay_code' => $pay_code
	        	];
	        	$re = Db::name('system_transaction_details_person')->insert($arr);   
            	//增加对应的账单收入
            	if($re){
            		$arrival = (float)sprintf("%.2f",$finbill['arrival'] + $insbill['receivable_online']);
    				$balance = (float)sprintf("%.2f",$arrival - $finbill['receivable']);
    				Db::name('system_financial_bill_person')->where(['id'=>$finbill['id']])->update(['arrival'=>$arrival,'balance'=>$balance,'status'=>3]);
    				Db::name('system_makeup_bill')->where(['id'=>$insbill['id']])->update(['arrival'=>$arrival,'balance'=>$balance,'payment_method'=>3,'status'=>4]);
            	}
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
            }
        }
    }
    
    
    
    
    /**
     * 修改个人增值账单状态
     * @param string $order_sn 订单编号
     * @param string $pay_at 支付时间
     * @param string $pay_no 支付交易单号
     * @param string $pay_code 真实订单号
     */
    private function appreciationbill_update($order_sn, $pay_at, $pay_no, $pay_code)
    {
    	$insbill = Db::name('system_appreciation_bill')->where(['code'=>$order_sn,'is_deleted'=>0,'status'=>[2,3]])->find();
        if ($insbill) {
            Db::startTrans();
            try {           	
				//更新财务账单
				$finbill = Db::name('system_financial_bill_person')->where(['bill_type'=>5,'jump_id'=>$insbill['id']])->find();
				if($insbill['cost_type'] == 1){
					$amount = $insbill['receivable_online'];
				}else{
					$amount = $insbill['receivable'];
				}
        		//添加明细
        		$arr = [
	        		'finbill_id' => $finbill['id'],
	        		'code' => $finbill['code'],
	        		'company_id' => $finbill['company_id'],
	        		'person_id' => $insbill['person_id'],
	        		'trade_type' => 1,
	        		'trade_mode' => 3,
	        		'date' => date('Y-m-d',$pay_at),
	        		'amount' => $amount,
	        		'cost_type' => $insbill['cost_type'],
	        		'pay_no' => $pay_no,
	        		'pay_code' => $pay_code
	        	];
	        	$re = Db::name('system_transaction_details_person')->insert($arr);   
            	//增加对应的账单收入
            	if($re){
            		$arrival = (float)sprintf("%.2f",$finbill['arrival'] + $amount);
    				$balance = (float)sprintf("%.2f",$arrival - $finbill['receivable']);
    				Db::name('system_financial_bill_person')->where(['id'=>$finbill['id']])->update(['arrival'=>$arrival,'balance'=>$balance,'status'=>3]);
    				Db::name('system_appreciation_bill')->where(['id'=>$insbill['id']])->update(['arrival'=>$arrival,'balance'=>$balance,'payment_method'=>3,'status'=>4]);
            	}
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
            }
        }
    }
    
}